package cn.vapor.sping.boot.rmiexporter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.rmi.RmiServiceExporter;

import javax.annotation.PostConstruct;
import java.rmi.RemoteException;
import java.util.Map;

/**
 * @author Wu Zhenwei
 * 2017/11/9
 * @since 1.8
 */
@Configuration
public class RmiAutoExporter implements ApplicationContextAware {

    private ApplicationContext context;

    private final static Logger logger = LoggerFactory.getLogger(RmiAutoExporter.class);

    @PostConstruct
    public void exporter() {
        Map<String, Object> beans = context.getBeansWithAnnotation(Exporter.class);
        beans.forEach((beanName, service) -> {
            Exporter exporter = service.getClass().getAnnotation(Exporter.class);
            String name = exporter.name();
            if (name.isEmpty()) {
                name = beanName;
            }
            int port = exporter.port();
            Class<?> serviceInterface = exporter.serviceInterface();
            RmiServiceExporter rse = new RmiServiceExporter();
            rse.setService(service);
            rse.setServiceInterface(serviceInterface);
            rse.setRegistryPort(port);
            rse.setServiceName(name);
            try {
                rse.afterPropertiesSet();
                logger.info(name + "服务注册到端口" + port);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        });
        this.context = null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
